package com.hspedu.dao_.dao;

import com.hspedu.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/4/12
 * @time 13:53
 */
public class BasicDao<T> {

    private QueryRunner queryRunner = new QueryRunner();

    public int update(String sql, Object... parameters){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            int affectedRows = queryRunner.update(connection, sql, parameters);
            return affectedRows;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.closeConnection(null,null,connection);
        }
    }

    /**
     *
     * @param sql           可以有占位符
     * @param clazz         传入类的Class对象
     * @param parameters    为占位符赋值
     * @return              根据传入类的Class对象返回集合
     */
    public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters){
        List<T> list = null;
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            list = queryRunner.query(connection,sql,new BeanListHandler<>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.closeConnection(null,null,connection);
        }
        return list;
    }

    /**
     * 查询单行多列
     * @param sql
     * @param clazz
     * @param parameters
     * @return
     */
    public T querySingle(String sql,Class<T> clazz, Object... parameters){
        Connection connection = null;
        T t = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            t = queryRunner.query(connection, sql, new BeanHandler<>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.closeConnection(null,null,connection);
        }
        return t;
    }

    /**
     * 查询单行单列
     * @param sql
     * @param parameters
     * @return
     */
    public Object queryScalar(String sql,Object... parameters){
        Connection connection = null;
        Object o = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            o = queryRunner.query(connection, sql, new ScalarHandler(), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtilsByDruid.closeConnection(null,null,connection);
        }
        return o;
    }
}
